import RuleChainApi from '@/api/ruleChain'
import { ProductTypeMapping } from '@/model/product.model'
import { Message } from 'element-ui'

const product = {
  namespaced: true,
  state: {
    type: '', // 产品类型：车端（场景类、模式类）、云端
    productInfo: {},
    loading: true,
    editEnable: false,
    nodeList: []
  },

  mutations: {
    save: (state, { name, value }) => { state[name] = value },
    updateProductInfoByKey: (state, { name, value }) => { state.productInfo[name] = value },
    updateProductInfo: (state, data) => {
      state.productInfo = data
    }
  },
  actions: {
    updateCCUList({ commit }, vehicles) {
      commit('updateProductInfoByKey', { name: 'ccuIdcVersionList', value: vehicles })
    },
    updateProductVehicles({ commit }, vehicles) {
      commit('updateProductInfoByKey', { name: 'oemList', value: vehicles })
    },
    updateSignalList({ commit }, list) {
      commit('updateProductInfoByKey', { name: 'optionalSignals', value: list })
    },

    updateProductInfo({ commit }, info) {
      commit('updateProductInfo', info)
    },

    async getProductInfo({ commit, state, dispatch }, id) {
      if (state.productInfo.id) {
        return state.productInfo
      } else {
        return await dispatch('getNewProductInfo', id)
      }
    },
    async getNewProductInfo({ commit, rootGetters, dispatch }, id) {
      const res = await RuleChainApi.getProductInfo(id)
      res.data.oemList = res.data.oemList || []
      res.data.ccuIdcVersionList = res.data.ccuIdcVersionList || []
      res.data.optionalSignals = res.data.optionalSignals || []
      // 车型继承自动兼容
      let isMerge = false
      res.data.defaultOemList?.forEach(item => {
        if (!res.data.oemList.some(oemItem => oemItem.modelCode === item.modelCode)) {
          res.data.oemList.push(item)
          isMerge = true
        }
      })
      isMerge && Message({ message: '车型不兼容，已自动合并' })
      commit('save', { name: 'type', value: ProductTypeMapping[res.data.productType] })
      commit('save', {
        name: 'editEnable',
        value: ((res, rootGetters) => {
          return rootGetters.userId === res.data.userId && ['0', '4', '6'].includes(res.data.productStatus)
        })(res, rootGetters)
      })
      commit('save', { name: 'productInfo', value: res.data })
      dispatch('getNodeList')
      return res.data
    },

    async getNodeList({ state, dispatch }) {
      if (state.nodeList.length) {
        return state.nodeList
      } else {
        return await dispatch('getNewNodeList')
      }
    },
    async getNewNodeList({ commit, state }) {
      const param = {
        modelIds: state.productInfo.ruleChainId,
        productType: state.productInfo.productType
      }
      const res = await RuleChainApi.getRuleNodeComponents(param)
      commit('save', { name: 'nodeList', value: res.data })
      return res
    }
  }
}

export default product
